import BaseSDK from "../base/BaseSDK";
import PlayerVO from "../../../game/player/PlayerVO";
import { ProtocolPool } from "../../../gamenet/protobufs/base/BaseProtocol";
import { UpdateUserInfo } from "../../../gamenet/protobufs/userprotocol/protocol_001";

interface AuthSetting { [authKey: string]: boolean };
/**
 * 微信小游戏sdk
 */
export default class WeChat extends BaseSDK {
    /** 显示右上角转发 */
    showShareMenu() {
        wx.showShareMenu({
            withShareTicket: true
        });
    }

    /** 隐藏右上角转发 */
    hideShareMenu() {
        wx.hideShareMenu();
    }

    /** 右上角转发信息 */
    onShareAppMessage() {
        let path = `resources/textures/share/1.jpg`;
        let raw = cc.url.raw(path);
        wx.onShareAppMessage(() => {
            return {
                title: `据说这关没多少人能过!`,
                imageUrl: cc.loader.md5Pipe.transformURL(raw),
            };
        });
    }

    /** 主动转发 */
    shareAppMessage() {
        let path = `resources/textures/share/1.jpg`;
        let raw = cc.url.raw(path);
        wx.shareAppMessage({
            title: `据说这关没多少人能过!`,
            imageUrl: cc.loader.md5Pipe.transformURL(raw),
        });
    }

    /** 静默登录, 默认开启右上角分享 */
    silentLogin(): Promise<string> {
        return new Promise((resolve, reject) => {
            wx.login({
                success: (data: { errMsg: string, code: string }) => {
                    console.log(`[Wechat] silentLogin --> `, data);
                    resolve(data.code);
                    this.showShareMenu();
                    this.onShareAppMessage();
                },
                fail: (err) => {
                    console.error(`[Wechat] silentLogin --> `, err);
                    reject(null);
                },
            });
        });
    }

    /** 获取用户信息, 如果用户没有授权，则进行授权登录再进行获取用户信息 */
    getUserInfo(): Promise<UpdateUserInfo> {
        return new Promise((resolve, reject) => {
            let getUserInfo = () => {
                wx.getUserInfo({
                    success: (res) => {
                        console.log(`[WeChat] --> 获取用户信息成功`, res);
                        let data = res.userInfo;
                        if(data){
                            let protocol = ProtocolPool.instance.getProtocol(UpdateUserInfo);
                            protocol.icon = data.avatarUrl;
                            protocol.city = data.city;
                            protocol.country = data.country;
                            protocol.sex = data.gender;
                            protocol.language = data.language;
                            protocol.nickName = data.nickName;
                            protocol.province = data.province;
                            console.log(`[WeChat] --> protocol`, protocol.msgType);
                            protocol.encodeAndSend().then((proto: UpdateUserInfo) => {
                                resolve(proto);
                            });
                        }else{
                            reject();
                        }
                    },
                    fail: (err) => {
                        console.log(`[WeChat] --> 获取用户信息失败`, err);
                        reject();
                    }
                });
            }
            this._getAuthSetting().then((authSetting: AuthSetting) => {
                let authFiled = `scope.userInfo`;
                let userInfoAuth = authSetting[authFiled];
                console.log(`[WeChat] --> 用户是否授权`, userInfoAuth, authSetting);
                let hasAuthKey = (authSetting as Object).hasOwnProperty(authFiled);
                if (userInfoAuth) {
                    getUserInfo();
                } else {
                    console.log(`[WeChat] --> 用户未授权,尝试询问用户授权`);
                    this._authorize(authFiled).then(() => {
                        console.log(`[WeChat] --> 用户授权成功`);
                        getUserInfo();
                    }).catch((err) => {
                        console.log(`[WeChat] --> 用户授权失败`, err, hasAuthKey);
                        if(hasAuthKey){
                            console.log(`[WeChat] --> 以前询问过, 开始引导授权`);
                            wx.openSetting({
                                fail: reject
                            });
                        }else{
                            reject();
                        }
                    });
                }
            });
        });
    };

    /** 获取授权信息 */
    private _getAuthSetting(): Promise<AuthSetting> {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success: (res: { errMsg: string, authSetting: { [authKey: string]: boolean }}) => {
                    console.log(`[Wechat] --> getUserInfo`, res);
                    resolve(res.authSetting);
                },
                fail: () => {
                    reject(null);
                }
            });
        });
    }

    /** 询问用户授权 */
    private _authorize(scope: string): Promise<any>{
        return new Promise((resolve, reject) => {
            wx.authorize({
                scope: scope,
                success: resolve,
                fail: reject
            });
        });
    }
}
